package com.ld.shieldsb.canalclient.handler.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import lombok.Data;

/**
 * RDB表映射配置
 *
 * @author rewerma 2018-11-07 下午02:41:34
 * @version 1.0.0
 */
@Data
public class MappingConfig implements AdapterConfig {

    private String dataSourceKey; // 数据源key

    private String destination; // canal实例或MQ的topic

    private String outerAdapterKey; // 对应适配器的key

    private boolean concurrent = false; // 是否并行同步

    private DbMapping dbMapping; // db映射配置

    @Override
    public AdapterMapping getMapping() {
        return dbMapping;
    }

    public void validate() {
        if (dbMapping.database == null || dbMapping.database.isEmpty()) {
            throw new NullPointerException("dbMapping.database");
        }
    }

    @Data
    public static class DbMapping implements AdapterMapping {

        private String database; // 数据库名或schema名
        private String table; // 表名
        private Map<String, String> targetPk = new LinkedHashMap<>(); // 目标表主键字段,key为目标表，value为源表
        private boolean mapAll = false; // 映射所有字段
        private String targetDb; // 目标库名
        private String targetTable; // 目标表名
        private Map<String, String> targetColumns; // 目标表字段映射，可以为目标表，value为源表

        private boolean caseInsensitive = false; // 目标表不区分大小写，默认是否

        private String etlCondition; // etl通用条件sql
        private String etlDelta; // etl增量条件

        private int readBatch = 5000;
        private int commitBatch = 5000; // etl等批量提交大小

        private Map<String, String> allMapColumns; // 缓存字段匹配关系

        public Map<String, String> getTargetColumns() {
            if (targetColumns != null) {
                targetColumns.forEach((key, value) -> {
                    if (StringUtils.isEmpty(value)) {
                        targetColumns.put(key, key);
                    }
                });
            }
            return targetColumns;
        }

    }
}
